﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Game
{
    public class SavingState : StateBase
    {
        public SavingState(DataBase.Manager db)
            : base(db)
        {
        }

        public void Activate(WorldScene scene)
        {
            GameScene = scene;
            Activate();
        }

        public override void Activate()
        {
            if (GameScene == null)
            {
                Log.Error("GameScene is null");
            }

            var mapObjects = DataBaseManager.GetMapObjects();
            if (ProgressBar != null)
            {
                ProgressBar.Value = 0;
                ProgressBar.Count = mapObjects.Count;
                ProgressBar.Caption = "Saving...";
            }

            //Saving
            foreach (var it in DataBaseManager.GetMapObjects())
            {
                ///
                /// Update Position and Orientation
                ///
                DataBase.Entities.MapObject item = it.Value;

                IDK.SceneNode node = GameScene.Core.GetScene().GetNode(item.name);

                IDK.Vector3 vPos = node.GetTransformation().GetLocalPosition();
                IDK.Quaternion vRot = node.GetTransformation().GetLocalOrientation();

                // write new position
                item.posX = vPos.x;
                item.posY = vPos.y;
                item.posZ = vPos.z;

                item.qX = vRot.x;
                item.qY = vRot.y;
                item.qZ = vRot.z;
                item.qW = vRot.w;

                if (ProgressBar != null)
                {
                    ProgressBar.Value = ProgressBar.Value + 1;
                }
            }

            //Flush to DB
            DataBaseManager.UpdateDataToDB();

            //Save gameobjects info
            SaveGameObject(DataBaseManager.LoadedMapName);
        }

        protected virtual void SaveGameObject(String name)
        {
            //do nothing
        }

        public override void Deactivate()
        {
            GameScene = null;
        }

        public override Transition Update(Events.ProcessUpdate evnt)
        {
            return Transition.Next;
        }
    }
}
